package cn.jhz.learn.blog.component.shiro;

import cn.jhz.learn.blog.util.JwtUtil;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.jose4j.jwt.MalformedClaimException;
import org.jose4j.jwt.consumer.InvalidJwtException;
import org.jose4j.lang.JoseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 该类可以确定提供的AuthenticationToken凭据是否与存储在系统中的相应帐户凭据相匹配
 *
 * @author machine_005
 * @version 1.0
 */
public class JwtCredentialsMatcher implements CredentialsMatcher {
    private Logger logger = LoggerFactory.getLogger(JwtCredentialsMatcher.class);
    /**
     * 如果提供的令牌凭据与存储的帐户凭据匹配，则返回 {@code true}，否则返回{@code false}。
     * @param token {@code AuthenticationToken}身份验证尝试期间提交的
     * @param info  {@code AuthenticationInfo}存储在系统中的
     * @return {@code true}如果提供的令牌凭据与存储的帐户凭据匹配,否则为{@code false}.
     */
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        try {
            return JwtUtil.getInstance().validated(token.getCredentials().toString(), (List<String>) token.getPrincipal());
        } catch (MalformedClaimException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        } catch (JoseException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        } catch (InvalidJwtException e) {
            e.printStackTrace();
        }
        return false;
    }
}
